package resp

import (
	"encoding/json"
	"encoding/xml"
	"gitee.com/kristas/booting-go/framework/common/util/lang"
	"gitee.com/kristas/booting-go/framework/common/util/list"
	"gitee.com/kristas/booting-go/framework/core/configure"
	"gitee.com/kristas/booting-go/framework/web"
	"gopkg.in/yaml.v3"
)

func ContentType(cType string) string {
	conf := new(web.Configure)
	configure.BindConfiguration(conf)
	if !lang.NewString(cType).Contains("charset") && shouldAppendCharset(cType) {
		return cType + "; charset=" + conf.Charset
	}
	return cType
}

func shouldAppendCharset(cType string) bool {
	return !list.NewSets(ContentBinaryHeaderValue, ContentWebassemblyHeaderValue, ContentRedirect).
		Exists(cType)
	//return cType != ContentBinaryHeaderValue &&
	//	cType != ContentWebassemblyHeaderValue &&
	//	cType != ContentRedirect
}

var JsonMarshaller Marshaller = func(data interface{}) []byte {
	bytes, _ := json.Marshal(data)
	return bytes
}

var YamlMarshaller Marshaller = func(data interface{}) []byte {
	files, _ := yaml.Marshal(data)
	return files
}

var XmlMarshaller Marshaller = func(data interface{}) []byte {
	files, _ := xml.Marshal(data)
	return files
}

var RawMarshaller Marshaller = func(data interface{}) []byte {
	files := lang.NewString(data).GetBytes()
	return files
}

var autoMarshaller = map[string]Marshaller{
	ContentJSONHeaderValue: JsonMarshaller,
	ContentXMLHeaderValue:  XmlMarshaller,
	ContentYAMLHeaderValue: YamlMarshaller,
}
